<template>
  <div class="panel right-middle">
    <div class="content" ref="chartRef"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'

const chartRef = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

// 计算每个系列的最小值和最大值
const getMinMax = (data: any[], key: string) => {
  const values = data.map(item => item[key])
  const min = Math.min(...values)
  const max = Math.max(...values)
  // 添加一些缓冲空间
  const range = max - min
  return {
    min: Math.floor(min - range * 0.1),
    max: Math.ceil(max + range * 0.1)
  }
}

// 模拟数据
// const generateData = () => {
//   const now = new Date()
//   const data = []
//   for (let i = 0; i < 24; i++) {
//     const time = new Date(now.getTime() - (23 - i) * 3600 * 1000)
//     data.push({
//       time: time.getHours() + ':00',
//       temperature: Math.random() * 5 + 18, // 18-23度
//       humidity: Math.random() * 15 + 55,   // 55-70%
//       light: Math.random() * 800 + 200     // 200-1000 lux
//     })
//   }
//   return data
// }
const generateData = () => {
  const now = new Date()
  const data = []

  // 模拟24小时数据，每小时一个点
  for (let i = 0; i < 24; i++) {
    const time = new Date(now.getTime() - (23 - i) * 3600 * 1000)
    const hour = time.getHours()

    // 温度模型：最低温出现在凌晨4点，最高温出现在下午3点
    const baseTemp = 15 // 基础温度
    const tempAmplitude = 8 // 温度波动幅度
    const phaseShift = 4 // 相位偏移（最低温时间）
    const temperature = baseTemp + tempAmplitude * Math.sin(Math.PI * (hour - phaseShift) / 12)
        + (Math.random() * 2 - 1) // 添加随机波动

    // 湿度模型：湿度与温度呈负相关
    const baseHumidity = 70
    const humidityAmplitude = 15
    const humidity = baseHumidity - humidityAmplitude * Math.sin(Math.PI * (hour - phaseShift) / 12)
        + (Math.random() * 5 - 2.5) // 添加随机波动
        + 0.5 * (temperature - baseTemp) // 温度影响湿度

    // 光照模型：只在白天有光照，中午最强
    let light = 0
    if (hour >= 6 && hour <= 18) {
      const lightPeak = 10000 // 中午最强光照
      const lightDuration = 12 // 白天时长
      const lightOffset = hour - 6 // 从6点开始计算
      light = lightPeak * Math.sin(Math.PI * lightOffset / lightDuration)
          + (Math.random() * 1000 - 500) // 添加随机波动
      light = Math.max(0, light) // 确保光照不小于0
    }

    data.push({
      time: time.getHours() + ':00',
      temperature: parseFloat(temperature.toFixed(1)),
      humidity: parseFloat(humidity.toFixed(1)),
      light: Math.round(light)
    })
  }

  return data
}
const initChart = () => {
  try {
    if (!chartRef.value) {
      console.error('图表容器未找到')
      return
    }
    
    // 确保容器有高度
    if (chartRef.value.clientHeight === 0) {
      console.error('图表容器高度为0')
      return
    }

    // 如果已经存在图表实例，先销毁
    if (chart) {
      chart.dispose()
    }
    
    // 确保容器可见
    if (chartRef.value.offsetParent === null) {
      console.error('图表容器不可见')
      return
    }

    chart = echarts.init(chartRef.value)
    const data = generateData()

    // 计算每个系列的最小值和最大值
    const tempRange = getMinMax(data, 'temperature')
    const humidityRange = getMinMax(data, 'humidity')
    const lightRange = getMinMax(data, 'light')

    const option = {
      tooltip: {
        trigger: 'axis',
        position: function (pt: any) {
          return [pt[0], '10%'];
        },
        axisPointer: {
          type: 'cross',
          label: {
            backgroundColor: '#6a7985'
          }
        },
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        borderColor: 'rgba(51, 255, 208, 0.3)',
        borderWidth: 1,
        padding: [8, 12],
        textStyle: {
          color: '#fff'
        },
        z: 9999,
        confine: true,  // 确保悬浮窗不会超出图表区域
        formatter: (params: any) => {
          let result = `<div style="font-size: 12px; color: #33ffd0; margin-bottom: 8px; font-weight: bold;">${params[0].axisValue}</div>`
          params.forEach((param: any) => {
            const color = param.color
            const name = param.seriesName
            const value = param.value
            const unit = name === '温度' ? '℃' : name === '湿度' ? '%' : 'lux'
            const unitPosition = name === '温度' ? 'center' : name === '湿度' ? 'center' : 'right'
            result += `
              <div style="display: flex; align-items: center; margin: 4px 0;">
                <span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${color}; margin-right: 8px;"></span>
                <span style="color: #fff; margin-right: 8px; min-width: 60px;">${name}</span>
                <span style="color: #33ffd0; display: flex; align-items: center; justify-content: ${unitPosition}; min-width: 60px; font-weight: bold;">
                  ${name === '温度' ? `${value.toFixed(1)}${unit}` : name === '湿度' ? `${value.toFixed(1)}${unit}` : `${value.toFixed(0)}${unit}`}
                </span>
              </div>
            `
          })
          return result
        }
      },
      legend: {
        data: ['温度', '湿度', '光照强度'],
        textStyle: {
          color: '#33ffd0',
          fontSize: 12
        },
        top: -2,
        itemWidth: 10,
        itemHeight: 10,
        itemGap: 15,
        padding: [5, 0, 5, 0]
      },
      grid: {
        top: '10%',
        left: '5%',
        right: '5%',
        bottom: '5%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: data.map(item => item.time),
        axisLine: {
          lineStyle: {
            color: '#33ffd0',
            width: 1
          }
        },
        axisLabel: {
          color: '#33ffd0',
          fontSize: 10,
          margin: 8
        },
        axisTick: {
          show: false
        }
      },
      yAxis: [
        {
          type: 'value',
          position: 'left',
          min: tempRange.min,
          max: tempRange.max,
          axisLine: {
            show: false
          },
          axisLabel: {
            show: false
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(51, 255, 208, 0.1)',
              type: 'dashed'
            }
          },
          axisTick: {
            show: false
          }
        },
        {
          type: 'value',
          position: 'right',
          min: humidityRange.min,
          max: humidityRange.max,
          axisLine: {
            show: false
          },
          axisLabel: {
            show: false
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        },
        {
          type: 'value',
          position: 'right',
          offset: 80,
          min: lightRange.min,
          max: lightRange.max,
          axisLine: {
            show: false
          },
          axisLabel: {
            show: false
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: false
          }
        }
      ],
      series: [
        {
          name: '温度',
          type: 'line',
          smooth: true,
          data: data.map(item => item.temperature),
          itemStyle: {
            color: '#ff6b6b',
            borderWidth: 0
          },
          lineStyle: {
            width: 2,
            shadowColor: 'rgba(255, 107, 107, 0.3)',
            shadowBlur: 10,
            shadowOffsetY: 5
          },
          symbol: 'circle',
          symbolSize: 6,
          emphasis: {
            itemStyle: {
              color: '#ff6b6b',
              borderColor: '#fff',
              borderWidth: 2
            }
          }
        },
        {
          name: '湿度',
          type: 'line',
          smooth: true,
          yAxisIndex: 1,
          data: data.map(item => item.humidity),
          itemStyle: {
            color: '#4ecdc4',
            borderWidth: 0
          },
          lineStyle: {
            width: 2,
            shadowColor: 'rgba(78, 205, 196, 0.3)',
            shadowBlur: 10,
            shadowOffsetY: 5
          },
          symbol: 'circle',
          symbolSize: 6,
          emphasis: {
            itemStyle: {
              color: '#4ecdc4',
              borderColor: '#fff',
              borderWidth: 2
            }
          }
        },
        {
          name: '光照强度',
          type: 'line',
          smooth: true,
          yAxisIndex: 2,
          data: data.map(item => item.light),
          itemStyle: {
            color: '#ffe66d',
            borderWidth: 0
          },
          lineStyle: {
            width: 2,
            shadowColor: 'rgba(255, 230, 109, 0.3)',
            shadowBlur: 10,
            shadowOffsetY: 5
          },
          symbol: 'circle',
          symbolSize: 6,
          emphasis: {
            itemStyle: {
              color: '#ffe66d',
              borderColor: '#fff',
              borderWidth: 2
            }
          }
        }
      ]
    }

    chart.setOption(option)
    console.log('图表初始化成功')
  } catch (error) {
    console.error('图表初始化失败:', error)
  }
}

// 定时更新数据
// let timer: number | null = null
// let initTimeout: number | null = null
//
// onMounted(async () => {
//   // 等待 DOM 更新完成
//   await nextTick()
//
//   // 延迟初始化，确保容器已经渲染
//   initTimeout = window.setTimeout(() => {
//     initChart()
//
//     // 每5秒更新一次数据
//     timer = window.setInterval(() => {
//       const data = generateData()
//       if (chart) {
//         try {
//           // 计算新的范围
//           const tempRange = getMinMax(data, 'temperature')
//           const humidityRange = getMinMax(data, 'humidity')
//           const lightRange = getMinMax(data, 'light')
//
//           chart.setOption({
//             xAxis: {
//               data: data.map(item => item.time)
//             },
//             yAxis: [
//               { min: tempRange.min, max: tempRange.max },
//               { min: humidityRange.min, max: humidityRange.max },
//               { min: lightRange.min, max: lightRange.max }
//             ],
//             series: [
//               {
//                 data: data.map(item => item.temperature)
//               },
//               {
//                 data: data.map(item => item.humidity)
//               },
//               {
//                 data: data.map(item => item.light)
//               }
//             ]
//           })
//         } catch (error) {
//           console.error('更新图表数据失败:', error)
//         }
//       }
//     }, 5000)
//   }, 300)
//
//   // 监听窗口大小变化
//   window.addEventListener('resize', () => {
//     if (chart) {
//       try {
//         chart.resize()
//       } catch (error) {
//         console.error('调整图表大小失败:', error)
//       }
//     }
//   })
// })
//
// onUnmounted(() => {
//   if (timer) {
//     clearInterval(timer)
//   }
//   if (initTimeout) {
//     clearTimeout(initTimeout)
//   }
//   if (chart) {
//     chart.dispose()
//   }
// })
let initTimeout: number | null = null

onMounted(async () => {
  await nextTick()

  initTimeout = window.setTimeout(() => {
    initChart()

    const data = generateData()
    if (chart) {
      try {
        // 计算新的范围
        const tempRange = getMinMax(data, 'temperature')
        const humidityRange = getMinMax(data, 'humidity')
        const lightRange = getMinMax(data, 'light')

        chart.setOption({
          xAxis: {
            data: data.map(item => item.time)
          },
          yAxis: [
            { min: tempRange.min, max: tempRange.max },
            { min: humidityRange.min, max: humidityRange.max },
            { min: lightRange.min, max: lightRange.max }
          ],
          series: [
            {
              data: data.map(item => item.temperature)
            },
            {
              data: data.map(item => item.humidity)
            },
            {
              data: data.map(item => item.light)
            }
          ]
        })
      } catch (error) {
        console.error('设置图表数据失败:', error)
      }
    }
  }, 300)

  window.addEventListener('resize', () => {
    if (chart) {
      try {
        chart.resize()
      } catch (error) {
        console.error('调整图表大小失败:', error)
      }
    }
  })
})

onUnmounted(() => {
  if (initTimeout) {
    clearTimeout(initTimeout)
  }
  if (chart) {
    chart.dispose()
  }
})
</script>

<style scoped>
.panel {
  height: 100%;
  width: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.content {
  flex: 1;
  width: 100%;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
}
</style>
